package com.yyt.transactional_demo.service;

import com.yyt.transactional_demo.domain.User;
import com.yyt.transactional_demo.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author yeyangtao created at 09:09 2020/10/17
 */
@Service
public class DemoService {
    @Resource
    private UserRepository repository;

    public void save(User user) {
        repository.saveAndFlush(user);
    }

    public User findOne(Long id) {
        return repository.findById(id).orElse(new User());
    }

    //@Transactional(rollbackFor = IndexOutOfBoundsException.class)
    public void demo() {
        User user = findOne(1L);
        user.setUserName("demo");
        save(user);
        int a = 1 / 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public void demo1() {
        User user = findOne(1L);
        user.setUserName("demo1");
        save(user);
        demo();
    }
}
